<template>
  <t-upload
    ref="uploadRef1"
    :auto-upload="false"
    :action="url"
    :headers="headers"
    :trigger-button-props="{ theme: 'primary', variant: 'base' }"
    accept=".xlsx, .xls"
    @success="onSuccess"
    :data="getData"
    :defaultFiles="defaultFiles"
  />
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import { useUserStore } from '@/store';
import { MessagePlugin } from 'tdesign-vue-next';

const props = defineProps<{
  file?: string | null;
  axios: string;
}>();

const emit = defineEmits(['update:file', 'success']);

const defaultFiles = computed(() => {
  if (!props.file) return [];
  return [{ url: props.file }];
});

const userStore = useUserStore();
const url = import.meta.env.VITE_API_URL_PREFIX + props.axios;
const headers = {
  Authorization: 'Bearer ' + userStore.token,
};

const uploadRef1 = ref();
const data = ref({});

const getData = () => {
  return data.value;
};

const uploadFiles = (row: any) => {
  data.value = row;
  uploadRef1.value.uploadFiles();
};

const onSuccess = (res: any) => {
  if (res.response.code === 200) {
    emit('success');
    MessagePlugin.success(res.response.msg);
  } else {
    MessagePlugin.error(`上传失败, ${res.response.msg}`);
  }
};

defineExpose({
  uploadFiles,
});
</script>
